package com.st.predicates;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * <p>title: com.wfx.predicates</p>
 * author zhuximing
 * description:
 */
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<Config> {


    public MyHeaderRoutePredicateFactory() {
        super(Config.class);
    }

    public Predicate<ServerWebExchange> apply(Config config) {



        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                //判断是否配置了value
                String value = config.getValue();
                if (value == null) {//没有配置value,请求头只要包含key即可，不关注具体的value值
                   if(exchange.getRequest().getHeaders().containsKey(config.getKey())){
                        return true;
                   }else{
                        return  false;
                   }

                }

                //1.获取请求头
                String httpHeadValue = exchange.getRequest().getHeaders().getFirst(config.getKey());
                if(value.equals(httpHeadValue)){
                    return  true;
                }else{
                    //如果返回false，不能访问该路由
                    return false;
                }


            }
        };
    }


    //谓词工厂参数获取方式

    public List<String> shortcutFieldOrder() {

        //- MyHeader=token,123
        //将token赋值给Config#key
        //将123赋值给Config#value
        return Arrays.asList("key","value");
    }
}
